package com.buka.util;

import cn.hutool.crypto.digest.MD5;
import com.buka.vo.LoginUserVo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

public class JWTUtil {

    //加密秘钥
    private static final String SECRET = "buka2401";

    //jwt 生成字符串 加自定义前缀
    private static final String PRE = "buka";

    //subject
    private static final String SUBJECT = "buka";

    //jwt 自动过期 过期时间  10分钟过期
    private static final long EXPIRE = 1000 * 60 * 60 * 24 * 100L;

    //生成令牌的方法
    public static String createJwt(LoginUserVo loginUserVo){
        if(null == loginUserVo){
            throw new NullPointerException("登录用户信息异常！");
        }
        Date date = new Date();
        String token = Jwts.builder().setSubject(SUBJECT)
                .claim("head_image", loginUserVo.getHeadImg())
                .claim("id", loginUserVo.getId())
                .claim("name", loginUserVo.getName())
                .claim("mail", loginUserVo.getMail())
                // 有效期 = 当前的签发时间 + 过期时间
                .setExpiration(new Date(date.getTime() + EXPIRE))
                .setIssuedAt(date)//签发日期
                .signWith(SignatureAlgorithm.HS256, SECRET).compact();

        return PRE + token;
    }

    //生成令牌的方法 增加设备信息
    public static String createJwtWithDevice(HttpServletRequest request,LoginUserVo loginUserVo){
        if(null == loginUserVo){
            throw new NullPointerException("登录用户信息异常！");
        }


        Date date = new Date();
        String token = Jwts.builder().setSubject(SUBJECT)
                .claim("head_image", loginUserVo.getHeadImg())
                .claim("id", loginUserVo.getId())
                .claim("name", loginUserVo.getName())
                .claim("mail", loginUserVo.getMail())
                .claim("deviceInfo",CommonUtil.getDeviceInfo(request))
                // 有效期 = 当前的签发时间 + 过期时间
                .setExpiration(new Date(date.getTime() + EXPIRE))
                .setIssuedAt(date)//签发日期
                .signWith(SignatureAlgorithm.HS256, SECRET).compact();

        return PRE + token;
    }


    //校验token
    public static Claims checkJWT(String token){
        Claims body = Jwts.parser().setSigningKey(SECRET)
                .parseClaimsJws(token.replace(PRE, ""))
                .getBody();
        return body;
    }



}
